from django.shortcuts import render, HttpResponse, redirect
from django import forms
from django.core.validators import RegexValidator


# Create your views here.


def ab_ajax(request):
    if request.method == 'POST':
        del_id = request.POST.get('del_id')
        return HttpResponse(f"来自于后端的消息:主键{del_id}对应的数据已经被删除")
    return render(request, 'ab_ajax.html')


class MyFrom(forms.Form):
    username = forms.CharField(label='用户名', min_length=3, max_length=8, error_messages=
    {'required': '不好意思 您的用户名不能为空'})
    password = forms.IntegerField(min_value=123, max_value=999999,
                                  # initial=666,
                                  # widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'})
                                  )
    confirm_pwd = forms.IntegerField(min_value=123, max_value=999999)
    email = forms.EmailField(required=False)  # 必须为邮箱格式   required=False 可修改默认不带该参数

    # phone = forms.CharField(validators=[
    #     RegexValidator(r'^[0-9]+$', '请输入数字'),
    #     RegexValidator(r'^159[0-9]+$', '数字必须以159开头')],)
    # 1.局部钩子校验用户名是否已存在
    def clean_username(self):
        username = self.cleaned_data.get('username')
        # 链接数据库完成数据查询 此处直接写死 model.User.objects.filter(username=username)
        if username == 'ckk':
            self.add_error('username', '用户名jason已存在')
        return username  # 钩子函数校验了谁 最后就应该返回谁(钩子函数 勾走了做一些数据操作之后还得还回来)

    # 2.全局钩子校验两次密码是否一致
    def clean(self):
        password = self.cleaned_data.get('password')
        confirm_pwd = self.cleaned_data.get('confirm_pwd')
        if not password == confirm_pwd:
            self.add_error('confirm_pwd', '两次密码不一致')
        return self.cleaned_data


def ab_form(request):
    form_obj = MyFrom()
    if request.method == 'POST':
        form_obj = MyFrom(request.POST)
        if form_obj.is_valid():
            return HttpResponse('所有的数据均符合要求')
    return render(request, 'ab_form.html', locals())  # 将产生的form类对象传递给html文件


# def ab_from(request):
#     if request.method == 'POST':
#         back_dic = {'username': '', 'password': ''}
#         username = request.POST.get('username')
#         password = request.POST.get('password')
#         if username == 'ckk':
#             back_dic['username'] = '用户不能是kk'
#         if password == '123':
#             back_dic['password'] = '密码不能为123'
#     return render(request, 'ab_from.html', locals())

# 如果还有form组件 必须写一个form类
# class RegForm(forms.Form):
#     username = forms.CharField(min_length=3, max_length=8)
#     password = forms.IntegerField()
#     email = forms.EmailField()

# modelform
from app01 import models


class RegModelFrom(forms.ModelForm):
    class Meta:
        model = models.UserInfo  # 直接指定想要检验数据的表
        fields = '__all__'
        labels = {
            "username": "用户名",
        }

    def clean_username(self):
        return self.cleaned_data.get('username')

    def clean(self):
        return self.cleaned_data


def register(request):
    regForm0bj = RegModelFrom()
    edit_obj = models.UserInfo.objects.filter(pk=1).first()
    if request.method == 'POST':
        regForm0bj = RegModelFrom(request.POST, instance=edit_obj)  # 传instance这个参数 就修改数据
        if regForm0bj.ismodelform_valid():
            # 如果是form组件 需要编写orm操作数据库
            regForm0bj.save()  # modelfrom 封装了save方法 自动执行数据库
    return render(request, 'register.html', locals())


def se_ck(request):
    res = HttpResponse()
    res.set_cookie('name', 'ckk')
    res.set_cookie('pwd', '123')
    return res


def se_gk(request):
    print(request.COOKIES.get('name'))
    print(request.COOKIES.get('pwd'))
    return HttpResponse('获取cookie数据')


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'ckk' and password == '123':
            # 从网址中获取用户登录之前想要访问的地址 也可能没有 用户直接访问的登录页面
            target_path = request.GET.get('next')
            if not target_path:
                # 用户登录之前没有想要访问的其他页面 跳转到一个默认的页面
                res = redirect('/home/')
            else:
                res = redirect(target_path)
            # res = HttpResponse("登录成功")
            res.set_cookie('name', username)
            return res
    return render(request, 'login.html')


def login_auth(func_name):
    def inner(request, *args, **kwargs):
        # print(request.path_info)
        # print(request.get_full_path())
        target_path = request.path_info
        if request.COOKIES.get('name'):
            res = func_name(request, *args, **kwargs)
            return res
        else:
            return redirect(f'/login/?next={target_path}')

    return inner


@login_auth
def home(request):
    # if request.COOKIES.get("name"):
    return HttpResponse("有资格观看才能看到此页面 默认也是此页面")
    # return redirect('/login/')
    # return HttpResponse("未登录用户无法查看home页面")


@login_auth
def index(request):
    # if request.COOKIES.get("name"):
    return HttpResponse("有资格查看")
    # return redirect('/login/')
    # return HttpResponse("未登录用户无法查看index页面")


@login_auth
def test(request):
    return HttpResponse("test页面 只有登录的用户才有资格观看")


def se_se(request):
    request.session['aaa'] = 123
    print(request.session.get('aaa'))
    # 获取session 和删除session
    # request.session.delete()
    # request.session.flush()
    return HttpResponse('设置session')


def ab_md(request):
    print('ab_md试图函数')
    return HttpResponse("嘿嘿嘿")


# def transfer(request):
#     if request.method == 'POST':
#         username = request.POST.get('username')
#         target_user = request.POST.get('target_user')
#         money = request.POST.get('money')
#         print(f'用户:{username}给{target_user}转账了{money}元')
#     return render(request, 'transfer.html')


from django.views.decorators.csrf import csrf_exempt, csrf_protect

"""
csrf_protent    必须校验csrf
csrf_exempt     必须不校验csrf
"""


# @csrf_protect
@csrf_exempt
def transfer(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        target_user = request.POST.get('target_user')
        money = request.POST.get('money')
        print(f'用户:{username}给{target_user}转账了{money}元')
    return render(request, 'transfer.html')


from django import views
from django.utils.decorators import method_decorator  # 方法装饰器


# @method_decorator(csrf_protect, name='post')   # 方式2
# @method_decorator(csrf_exempt, name='post')
class MyTransfer(views.View):
    # @method_decorator(csrf_protect)  # 方式3
    @method_decorator(csrf_exempt)  # 方式3
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, requset):
        return render(requset, 'transfer.html')

    # @method_decorator(csrf_protect)   # 方式1
    # @method_decorator(csrf_exempt)
    def post(self, request):
        username = request.POST.get('username')
        target_user = request.POST.get('target_user')
        money = request.POST.get('money')
        print(f'用户:{username}给{target_user}转账了{money}元')
        return HttpResponse('哈哈哈')


# 注意 针对csrf_exempt 在CBV中只有一种方式可以生效(特例) 只能在dispatch方法上装

from django.contrib import auth
from django.contrib.auth.models import User


def auth_reg(request):
    username = 'mj'
    password = 123
    # 创建用户
    res = auth.authenticate(username=username)
    if res:
        return HttpResponse('用户名已存在')
    # 添加数据
    # User.objects.create_user(username=username, password=password)  # 创建普通用户 密码自动加密
    User.objects.create_superuser(username=username, password=password, email='123@qq.com')  # 创建管理员 邮箱必填
    return HttpResponse('注册功能')


def auth_login(request):
    username = 'ckk'
    password = 123
    # 判断用户名和密码是否正确
    user_obj = auth.authenticate(username=username, password=password)
    if not user_obj:
        return HttpResponse('用户名或密码错误')
    # print(user_obj)       # 用户名密码正确直接返回数据对象
    # print(user_obj.username)
    # print(user_obj.password)
    # 保存用户登录状态
    auth.login(request, user_obj)  # 自动操作django_session 记录相关操作
    return HttpResponse('登录成功')


from django.contrib.auth.decorators import login_required


@login_required(login_url='/login/')  # 局部修改跳转地址
def auth_home(request):
    print(request.user)
    print(request.user.is_authenticated)
    return HttpResponse('只有登录的用户才可以查看 home')


@login_required(login_url='/transfer/')
def auth_index(request):
    return HttpResponse('只有登录的用户才可以查看 index')


@login_required
def auth_test(request):
    return HttpResponse('test页面')


def auth_setpwd(request):
    old_pwd = '123'
    new_pwd = '321'
    # 检验愿密码是否正确
    is_right = request.user.check_password(old_pwd)
    if not is_right:
        return HttpResponse('愿密码错误')
    request.user.set_password(new_pwd)
    request.user.save()


@login_required
def auth_logout(request):
    auth_login(request, request.user)      # 自动删除会话cookie
    return HttpResponse('退出登录')

